<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\android\v8;


use app\api\model\Common;


use app\api\model\SchemeCollection;
use app\api\model\schemeMaster;
use constant\config;
use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use app\api\model\Authority;


class UrbanDistrict extends Controller
{
    protected $us;

    public function _initialize()
    {
        $this->us = Authority::check(1);
    }



    /*
     * 获取小区
     */
    public function quartersList()
    {
        $city = Authority::param(['city', 'name']);

        if (Cache::get($city['city'] . 'city')) {
            $list = Cache::get($city['city'] . 'city');
        } else {
            $list = \db('house', config('database.zong'))->where('city', $city['city'])->field('id,name,city as cityId,area')->select();
            Cache::set($city['city'] . 'city', $list);
        }
        if ($city['name'] != '') {
            $arr = array();
            foreach ($list as $k => $v) {
                if (strstr($v['name'], $city['name']) !== false) {
                    array_push($arr, $v);
                }
            }
            $list = $arr;
        }

        r_date($list, 200);
    }

    /*
     * 获取户型
     * Db::connect($this->shopowner_db)->name('payment')
        ->field('orders_id,SUM(money) as payment, SUM(material) as main_payment, SUM(agency_material) as agent_payment,SUM(IF(cleared_time>0,material,0)) as main_payment_ok,SUM(IF(cleared_time>0,agency_material,0)) as agent_payment_ok')
        ->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')
        ->group('orders_id')
        ->buildSql();
     */
    public function HouseType(Common $common)
    {

        r_date($common->HouseData(), 200);
    }

    /*
     * 方案标签
     */
    public function programme()
    {
        $city = Authority::param(['ids']);
        $labelList = db('scheme_label_top', config('database.zong'))->field('id,title')->whereIn('id',$city['ids'])->whereNull('delete_time')->select();
        $schemeLabel = db('scheme_label', config('database.zong'))->field('id,title,pid,classification')->whereNull('delete_time')->select();
        foreach ($labelList as $k => $value) {
            foreach ($schemeLabel as $j => $l) {
                if ($value['id'] == $l['pid']) {
                    if ($l['classification'] == 1) {
                        $labelList[$k]['position'][] = $l;
                        foreach ($labelList[$k]['position'] as $p => $item) {
                            unset($labelList[$k]['position'][$p]['pid'], $labelList[$k]['position'][$p]['classification']);
                        }
                    }
                    if ($l['classification'] == 2) {
                        $labelList[$k]['problem'][] = $l;
                        foreach ($labelList[$k]['problem'] as $p => $item) {
                            unset($labelList[$k]['problem'][$p]['pid'], $labelList[$k]['problem'][$p]['classification']);
                        }
                    }
                }
            }
        }

        r_date($labelList, 200);
    }

    /*
     * 搜索中的方案标签
     */
    public function searchProgramme(Common $common)
    {
        $labelList = db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->select();
        $schemeLabel = db('scheme_label', config('database.zong'))->field('id,title')->where('classification', 1)->group('title')->whereNull('delete_time')->select();

        r_date(['houseType' => $common->HouseData(), 'problem' => $labelList, 'schemeLabel' => $schemeLabel], 200);
    }
    /*
     * 方案大师问题一级
     */
    public function schemeLabelTop()
    {
        $labelList = db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->select();


        r_date($labelList, 200);
    }

    /*
     * 方案大师创建
     */
    public function SchemeMasterCreation()
    {
        $paper = Request::instance()->post();
        $parameter = $paper;
        Db::connect(config('database.zong'))->startTrans();
//        $communityName = json_decode($parameter['communityName'], true);
//        $project = json_decode($parameter['project'], true);
//        $img = json_decode($parameter['img'], true);
//        $houseType = json_decode($parameter['houseType'], true);
//        $tag = json_decode($parameter['tag'], true);
//        $category = json_decode($parameter['category'], true);
        $communityName =$parameter['communityName'];
        $project = $parameter['project'];
        $img =$parameter['img'];
        $houseType = $parameter['houseType'];
        $tag = $parameter['tag'];
        $category =$parameter['category'];
        if (config('city') == 'cd') {
            $city = 241;
        } elseif (config('city') == 'wh') {
            $city = 172;
        } elseif (config('city') == 'gy') {
            $city = 262;
        } elseif (config('city') == 'cq') {
            $city = 239;
        }elseif (config('city') == 'sz') {
            $city = 202;
        }elseif (config('city') == 'sh') {
            $city = 375;
        }
        try {
            if ($paper['schemeId'] == 0) {
                $schemeLabel = Db::connect(config('database.zong'))->table('scheme_master')->insertGetId([
                    'name' => $parameter['name'],
                    'info' => $parameter['info'],
                    'day' => $parameter['day'],
                    'creation_time' => time(),
                    'user_id' => $this->us['user_id'],
                    'city_id' => empty($communityName[0]['cityId']) ? $city : $communityName[0]['cityId'],
                    'area' => $communityName[0]['area'],
                    'scheme_no' => 'YNWX' . date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                ]);
            } else {
                Db::connect(config('database.zong'))->table('scheme_master')->where(['plan_id' => $paper['schemeId'], 'user_id' => $this->us['user_id']])->update(['name' => $parameter['name'],
                    'info' => $parameter['info'],
                    'day' => $parameter['day'],
                    'city_id' => empty($communityName[0]['cityId']) ? $city : $communityName[0]['cityId'],
                    'area' => $communityName[0]['area'],
                ]);

                Db::connect(config('database.zong'))->table('scheme_project')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_img')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_community')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_house')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_tag')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_category')->where('plan_id', $paper['schemeId'])->delete();
                $schemeLabel = $paper['schemeId'];

            }


            //方案大师项目添加
            foreach ($project as $item) {
                foreach ($item['data'] as $value){
                    Db::connect(config('database.zong'))->table('scheme_project')->insert([
                        'plan_id' => $schemeLabel,
                        'projectId' => $value['projectId'],
                        'projectMoney' => $value['projectMoney'],
                        'projectTitle' => $value['projectTitle'],
                        'category' => $value['tao'],
                        'company' => $value['title'],
                        'agency' => $value['agency'],
                        'to_price' => sprintf('%.2f', $value['number'] * $value['projectMoney']),
                        'square' => $value['number'],
                        'remarks' => isset($value['remarks']) ? $value['remarks'] : '',
                        'grouping' => isset($item['title']) ? $item['title'] : '',
                    ]);
                }

            }
            //方案大师图片添加

            foreach ($img as $item) {
                Db::connect(config('database.zong'))->table('scheme_img')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'title' => $item['title'],
                    'path' => $item['path'],
                ]);
            }

            foreach ($communityName as $item) {
                Db::connect(config('database.zong'))->table('scheme_community')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'community' => $item['id'],
                    'name' => $item['name'],
                    'area' => $item['area'],
                ]);

            }

            foreach ($houseType as $item) {

                Db::connect(config('database.zong'))->table('scheme_house')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'house' => $item['id'],
                    'name' => $item['title'],
                ]);


            }

            foreach ($tag as $item) {

                foreach ($item['position'] as $value) {
                    Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'tag' => $value['id'],
                        'name' => $value['title'],
                        'type' => 1,
                        'pid' => $item['id'],
                    ]);
                }
                foreach ($item['problem'] as $value) {
                    Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'tag' => $value['id'],
                        'name' => $value['title'],
                        'type' => 2,
                        'pid' => $item['id'],
                    ]);
                }

            }
            foreach ($category as $item) {
                Db::connect(config('database.zong'))->table('scheme_category')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'category_id' => $item['id'],
                    'category_name' => $item['title'],
                ]);
            }
            Db::connect(config('database.zong'))->commit();
            r_date($schemeLabel, 200);
        } catch (Exception $exception) {
            Db::connect(config('database.zong'))->rollback();
            r_date(null, 300, $exception->getMessage());
        }


    }

    /*
     * 是否全部可见
     */
    public function verification()
    {
        $city = Authority::param(['isVisible', 'schemeId']);
        if ($city['isVisible'] == 'true') {
            $private = 1;
        } else {
            $private = 0;
        }
        db('scheme_master', config('database.zong'))->where('plan_id', $city['schemeId'])->update(['private' => $private]);
        r_date(null, 200);

    }

    public function SchemeMasterCreationInfo(schemeMaster $schemeMaster)
    {
        $city = Authority::param(['id']);

        $rows = $schemeMaster->with('schemeProject')
            ->with('schemeProject')
            ->with('schemeImg')
            ->with('schemeCommunity')
            ->with('schemeHouse')
            ->with('city')
            ->with('county')
            ->with('user')
            ->with('schemeTag')
            ->with(['SchemeCollection' => function ($query) {
                $query->where('scheme_collection.user_id', $this->us['user_id']);
            }])
            ->with('schemeCategory')
            ->where('scheme_master.plan_id', $city['id'])
            ->find()->toArray();
        $scheme_project=$rows['scheme_project'];
        $tageList = [];
        if ($rows['scheme_tag']) {
            $result = array();
            foreach ($rows['scheme_tag'] as $k => $v) {
                $result[$v['pid']][] = $v;
            }

            foreach ($result as $k => $list) {
                $schemeTag['id'] = $k;

                $schemeTag['position'] = $result[$k];
                unset($rows['scheme_tag']);
                $tageList[] = $schemeTag;
            }
        }
        if ($rows['scheme_project']) {
            $title=array_unique(array_column($rows['scheme_project'],'grouping'));

            $result= array();
            foreach ($title as $key => $info) {
                foreach ($rows['scheme_project'] as  $item) {
                    if($info==$item['grouping']){
                        $result[$key]['title'] = $info;
                        $result[$key]['id'] = 0;
                        $result[$key]['data'][] = $item;
                    }

                }
            }

        }

        unset($rows['scheme_project']);
        $rows['scheme_project']= array_merge($result);
        foreach ($rows['scheme_community'] as $k => $v) {
            $rows['scheme_community'][$k]['cityId'] = $rows['city_id'];

        }

        $rows['scheme_tag'] = $tageList;
        $rows['creation_time'] = date('Y-m-d H:i:s', $rows['creation_time']);
        $rows['address'] = $rows['city']['city'] . '-' . $rows['county']['county'];
        $rows['offer'] = array_sum(array_column($scheme_project, 'to_price'));
        $scheme_house = isset($rows['scheme_house'][0]['name']) ? $rows['scheme_house'][0]['name'] : '全部';
        $rows['briefIntroduction'] = $scheme_house . '|' . $rows['user']['username'];
        $rows['collection'] = empty($rows['scheme_collection']) ? 0 : 1;
        r_date($rows, 200);

    }

    /*
     * 方案大师列表查询
     * type 等于0系统方案 1收藏方案 2使用过的方案 3预设方案   name小区  方案类别category  House户型 position位置,title 编号
     */

    public function SchemeMasterCreationList(schemeMaster $schemeMaster)
    {

        $data = Authority::param(['type', 'name', 'category', 'House', 'position', 'title']);
        $order = Request::instance()->post();;
        $house = json_decode($data['House'], true);
        $house = !empty($house) ? array_column($house, 'id') : '';
        $name = json_decode($data['name'], true);
        $name = !empty($name) ? array_column($name, 'id') : '';
        $position = json_decode($data['position'], true);
        $position = !empty($position) ? array_column($position, 'title') : '';
        $category = json_decode($data['category'], true);
        $category = !empty($category) ? array_column($category, 'id') : '';
        $pos = [];
        $house_id = [];
        $rows = $schemeMaster
            ->join('city', 'city.city_id=scheme_master.city_id', 'left')
            ->join('county', 'county.county_id=scheme_master.area', 'left')
            ->join('user', 'user.user_id=scheme_master.user_id', 'left');
        if (isset($order['orderId']) && $order['orderId'] != 0) {
            $scheme_category = db('cc_scheme_label', config('database.zong'))->join('scheme_label_top','scheme_label_top.pid=cc_scheme_label.pro_id','left')
                ->where('order_id', $order['orderId'])
                ->field('scheme_label_top.id as topId,cc_scheme_label.*')
                ->select();

            $pos=array_column($scheme_category,'topId');
            $house_id=array_column($scheme_category,'house_id');
//            foreach ($scheme_category as $p) {
//                if($p['select']==1){
//                    $pos[] = $p['topId'];
//                }
//
//            }
        }
        if (!empty($pos)) {
            $scheme_category = db('scheme_category', config('database.zong'));
            $scheme_category->whereIn('category_id', $pos)->group('plan_id');
            $scheme_category = $scheme_category->column('plan_id');

            if (!empty($scheme_category)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_category);
            }else{
                $rows->whereIn('scheme_master.plan_id', '');
            }

        }
        if (!empty($house_id)) {
            $scheme_community = db('scheme_community', config('database.zong'))->whereIn('community', $house_id)->group('plan_id')->column('plan_id');
            $scheme_communityUnlimited = db('scheme_community', config('database.zong'))->where('community', 0)->group('plan_id')->column('plan_id');
            $scheme_community=array_merge($scheme_community,$scheme_communityUnlimited);
            if (!empty($scheme_community)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_community);
            }else{
                $rows->whereIn('scheme_master.plan_id', '');
            }
        }
        if (!empty($category)) {

            $scheme_category = db('scheme_category', config('database.zong'));
            $scheme_category->whereIn('category_id', $category)->group('plan_id');
            $scheme_category = $scheme_category->column('plan_id');

            if (!empty($scheme_category)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_category);
            }else{
                $rows->whereIn('scheme_master.plan_id', '');
            }

        }
        /*
         * 方案大师适用户型
         */
        if (!empty($house)) {
            $nameCount = implode($house, ',');
            if ($nameCount == 9) {
                $schemeHouse = db('scheme_house', config('database.zong'))->group('plan_id')->column('plan_id');
            } else {
                $schemeHouse = db('scheme_house', config('database.zong'))->whereIn('house', $house)->group('plan_id')->column('plan_id');
            }
            if (!empty($schemeHouse)) {
                $rows->whereIn('scheme_master.plan_id', $schemeHouse);
            }else{
                $rows->whereIn('scheme_master.plan_id', '');
            }
        }

        if (!empty($position)) {
            $schemeTag = [];
            foreach ($position as $item) {
                $schemeTag[] = db('scheme_tag', config('database.zong'))
                    ->where(['name' => ['like', "%{$item}%"]])->group('plan_id')->column('plan_id');
            }
            $schemeTag = array_reduce($schemeTag, 'array_merge', array());
            if (!empty($schemeTag)) {
                $rows->whereIn('scheme_master.plan_id', $schemeTag);
            }else{
                $rows->whereIn('scheme_master.plan_id', '');
            }

        }
        /*
                 * 方案大师适小区
                 */
        if (!empty($name)) {
            $nameCount = implode($name, ',');
            if ($nameCount == 0) {
                $scheme_community = db('scheme_community', config('database.zong'))->group('plan_id')->column('plan_id');

            } else {
                $scheme_community = db('scheme_community', config('database.zong'))->whereIn('community', $name)->group('plan_id')->column('plan_id');
            }
            if (!empty($scheme_community)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_community);
            }else{
                $rows->whereIn('scheme_master.plan_id', '');
            }
        }

        if ($data['title'] != '') {
            $scheme_community = db('scheme_community', config('database.zong'))->where('name', 'like', "%{$data['title']}%")->group('plan_id')->column('plan_id');
            $rows->where(function ($query) use ($data, $scheme_community) {
                $query->whereIn('scheme_master.plan_id', $scheme_community)->whereOr('scheme_master.scheme_no', 'like', "%{$data['title']}%");
            });


        }
//        if (config('city') == 'cd') {
//            $city = 241;
//        } elseif (config('city') == 'wh') {
//            $city = 172;
//        } elseif (config('city') == 'gy') {
//            $city = 262;
//        } elseif (config('city') == 'cq') {
//            $city = 239;
//        }

        if ($data['type'] == 0) {
            $rows->where(function ($query) {
                $query->where('scheme_master.private', 1)->whereOr('scheme_master.user_id', $this->us['user_id']);;

            });
        } elseif ($data['type'] == 1) {
            $rows->join('scheme_collection', 'scheme_master.plan_id=scheme_collection.plan_id', 'right')
                ->whereNull('scheme_collection.delete_time')
                ->where('scheme_collection.user_id', $this->us['user_id']);
        } elseif ($data['type'] == 2) {
            $rows->join('scheme_use', 'scheme_master.plan_id=scheme_use.plan_id', 'right')

                ->where('scheme_use.user_id', $this->us['user_id'])
                ->group('scheme_use.plan_id');
        } elseif ($data['type'] == 3) {
            $rows->where('scheme_master.user_id', $this->us['user_id']);

        }

        $rows = $rows->field('scheme_master.*,FROM_UNIXTIME(scheme_master.creation_time) as creationTime,city.city,county.county,user.username')->where('scheme_master.state', 1)->group('plan_id')
            ->order('scheme_master.plan_id desc')->select();

        $array = [];
        foreach ($rows as $k => $list) {

            $tolerable['address'] = $list['city'] . '-' . $list['county'];
            $tolerable['creationTime'] = $list['creationTime'];
            $tolerable['id'] = $list['plan_id'];
            $tolerable['title'] = $list['name'];
            $scheme_house = isset($list['scheme_house'][0]['name']) ? $list['scheme_house'][0]['name'] : '全部';
            $tolerable['briefIntroduction'] = $scheme_house . '|' . $list['username'];
            $tolerable['scheme_tag'] = $list['scheme_tag'];
            $tolerable['ConstructionPeriod'] = $list['day'];
            $tolerable['agency'] =  Db::connect(config('database.zong'))->table('scheme_project')->where('plan_id',$list['plan_id'])->where('agency',1)->count();
            $tolerable['offer'] = array_sum(array_column($list['scheme_project'], 'to_price'));
            $array[] = $tolerable;
        }
        r_date($array, 200);

    }

    /*
     * 收藏
     */
    public function Collection(SchemeCollection $schemeCollection)
    {
        $data = Authority::param(['id']);
        if (config('city') == 'cd') {
            $city = 241;
        } elseif (config('city') == 'wh') {
            $city = 172;
        } elseif (config('city') == 'gy') {
            $city = 262;
        } elseif (config('city') == 'cq') {
            $city = 239;
        }
        $Collection = $schemeCollection::all(['plan_id' => $data['id'], 'user_id' => $this->us['user_id'], 'city' => $city]);

        if ($Collection) {
            foreach ($Collection as $item) {
                $res = $schemeCollection::destroy($item->id);
            }

        } else {
            $res = $schemeCollection::create([
                'plan_id' => $data['id'],
                'creation_time' => time(),
                'city' => $city,
                'user_id' => $this->us['user_id'],
            ]);
        }
        if ($res) {
            r_date(null, 200);
        } else {
            r_date(null, 300);
        }

    }

    /*
     * 方案大师交互标准
     */
    public function getCustomList()
    {
        $data = Request::instance()->post();
        $capital = json_decode($data['projects'], true);
        $capitalList=[];
        foreach ($capital as $k => $item) {
            $capitalList[$k]['class_b'] = $item['projectTitle'];
            $capitalList[$k]['capital_id'] = 0;
            $capitalList[$k]['auxiliary_id'] = $item['projectId'];
            $capitalList[$k]['auxiliary_ids'] = '';
            $serial = db('detailed')->where('detailed_id', $item['projectId'])->value('serial');
            $auxiliary_relation = db('auxiliary_relation')
                ->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_relation.auxiliary_interactive_id and  auxiliary_interactive.parents_id=0', 'left')
                ->where('auxiliary_relation.serial_id', $serial)
                ->where('auxiliary_interactive.pro_types', 0)
                ->field('auxiliary_interactive.title,auxiliary_interactive.id')
                ->select();

            if ($auxiliary_relation) {
                foreach ($auxiliary_relation as $l => $key) {
                    $capitalList[$k]['data'][] = [
                        'id' => $key['id'],
                        'title' => $key['title'],
                    ];
                    $auxiliary_interactive = db('auxiliary_interactive')
                        ->whereIn('auxiliary_interactive.parents_id', $key['id'])
                        ->field('auxiliary_interactive.id, auxiliary_interactive.title')->select();
                    foreach ($auxiliary_interactive as $p => $value) {

                        $auxiliary_interactive[$p]['state'] = 3;
                        $auxiliary_interactive[$p]['node_id'] = 0;
                        $auxiliary_interactive[$p]['auxiliary_delivery_schedule_id'] = 0;

                    }
                    $capitalList[$k]['data'][$l]['data'] = array_merge($auxiliary_interactive);
                }
            } else {
                $capitalList[$k]['data'] = [];
            }

        }
        r_date(array_values($capitalList), 200);
    }

}